<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>async与await结合</title>
</head>

<body>
    <button id="btn">点击获取段子</button>
    <div id="duanzi"></div>
    <script>
        function sendGETAJAX(url) {
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest()
                xhr.responseType = 'json'
                xhr.open('GET', url)
                xhr.send()
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            resolve(xhr.response)
                        } else {
                            reject(xhr.status)
                        }
                    }
                }
            })
        }
        // 获取按钮
        let btn = document.getElementById('btn')
        let duanziDiv = document.getElementById('duanzi')
        btn.addEventListener('click', async () => {
            // 获取段子信息
            let duanzi = await sendGETAJAX('https://api.apiopen.top/getJoke')
            let result = duanzi.result
            let content = ''
            for (let i = 0, length = result.length; i < length; i++) {
                // 发生了问题，所有的结果都无法加载图片，服了
                content += `<p>${result[i].name}</p><img src=${result[i].images}/> <p>${result[i].text}</p> `
            }
            duanziDiv.innerHTML = content
            console.log(duanzi)
        })
    </script>
</body>

</html>